#include "timeout_conf.h"
#include "adc_driver.h"
#include "systime.h"
#include "device.h"

#define TIME_CFG_UPDATE_MS 20 // 单位ms,time设定值的更新时间

// 时间阈值--单位
#define TIMEOUT_30MIN 800 // 3档    实际测量814
#define TIMEOUT_15MIN 700 // 2 档   实际测量786
#define TIMEOUT_5MIN 600  // 1档    实际测量661
#define TIMEOUT_30S 450   // 0档    实际测量510

typedef enum
{
    TIME_STATE_INIT,
    TIME_STATE_UPDATE,

} TIME_STATE_E;

static struct
{
    timestamp_t time;
    TIME_STATE_E state;
    TIMEOUT_LEVEL sec_val;
} timeout_conf;

static uint16_t get_timeout_level(void);

void timeout_init(void)
{
    timeout_conf.state = TIME_STATE_INIT;
    timeout_conf.sec_val = TIMEOUT_LEVEL_5MIN;

    // just for debug
    printf("time_cfg threshold 30MIN: %d \r\n", TIMEOUT_30MIN);
    printf("time_cfg threshold 15MIN: %d \r\n", TIMEOUT_15MIN);
    printf("time_cfg threshold 5MIN: %d \r\n", TIMEOUT_5MIN);
}

TIMEOUT_LEVEL timeout_conf_get_sec(void)
{
    return timeout_conf.sec_val;
}

void timeout_level_get_task(void)
{
    switch (timeout_conf.state)
    {
    case TIME_STATE_INIT:
        timeout_conf.sec_val = get_timeout_level(); // 获取初始时间
        relative_time_add_ms(&timeout_conf.time, TIME_CFG_UPDATE_MS);
        //printf("the TIME position:%d \r\n", timeout_conf.sec_val);
        timeout_conf.state = TIME_STATE_UPDATE;
        break;
    case TIME_STATE_UPDATE:
        if (is_relative_time_timeout(&timeout_conf.time))
        {
            timeout_conf.sec_val = get_timeout_level();

            relative_time_add_ms(&timeout_conf.time, TIME_CFG_UPDATE_MS);
        }
        break;
    }
}

static TIMEOUT_LEVEL get_timeout_level(void)
{
    uint16_t val = get_time_val();

    if (val <= TIMEOUT_5MIN)
        return TIMEOUT_LEVEL_30S;
    else if (val <= TIMEOUT_15MIN)
        return TIMEOUT_LEVEL_5MIN;
    else if (val <= TIMEOUT_30MIN)
        return TIMEOUT_LEVEL_15MIN;
    else
        return TIMEOUT_LEVEL_30MIN;
}
